package com.cskaoyan.market.controller;

import com.cskaoyan.market.db.domain.MarketCategory;
import com.cskaoyan.market.service.MarketCategoryService;
import com.cskaoyan.market.service.MarketCategoryServiceImpl;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/admin/category/*")
public class AdminCategoryController extends HttpServlet {
    private MarketCategoryService categoryService = new MarketCategoryServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/category/", "");
        if ("list".equals(op)) {
            list(req, resp);
        } else if ("l1".equals(op)) {
            l1(req, resp);
        }
    }

    private void l1(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Map<String, Object> data = categoryService.primaryCategoryList();
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.ok(data)));
    }

    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Map<String, Object> data = categoryService.list();
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.ok(data)));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/category/", "");
        if ("create".equals(op)) {
            create(req, resp);
        } else if ("update".equals(op)) {
            update(req, resp);
        } else if ("delete".equals(op)) {
            delete(req, resp);
        }
    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = req.getReader().readLine();
        String idParam = JacksonUtil.parseString(requestBody, "id");
        Integer id = null;

        // 校验
        try {
            id = Integer.parseInt(idParam);
        } catch (NumberFormatException e) {
            resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.badArgument()));
            return;
        }

        // 修改数据库中的数据
        categoryService.delete(id);
        // 返回响应信息
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.ok()));
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = req.getReader().readLine();
        String idParam = JacksonUtil.parseString(requestBody, "id");
        String name = JacksonUtil.parseString(requestBody, "name");
        String keywords = JacksonUtil.parseString(requestBody, "keywords");
        String desc = JacksonUtil.parseString(requestBody, "desc");
        String iconUrl = JacksonUtil.parseString(requestBody, "iconUrl");
        String picUrl = JacksonUtil.parseString(requestBody, "picUrl");
        String level = JacksonUtil.parseString(requestBody, "level");
        String pidParam = JacksonUtil.parseString(requestBody, "pid");
        String children = JacksonUtil.parseString(requestBody, "children");
        Integer id = null;
        Integer pid = null;

        // 校验
        if ("L2".equals(level) && pidParam == null) {
            // 修改二级类目时pid不能为空
            resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.badArgument()));
            return;
        }
        try {
            id = Integer.parseInt(idParam);
            pid = Integer.parseInt(pidParam);
        } catch (NumberFormatException e) {
            resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.badArgument()));
            return;
        }
        if (StringUtils.isEmpty(name) || name.isEmpty()) {
            Object fail = ResponseUtil.fail(404, "类目名称不能为空");
            resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(fail));
            return;
        }
        if ("L2".equals(level) && children != null && !children.isEmpty()) {
            // 一级目录修改为二级目录时必须保证它没有子目录
            resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.badArgumentValue()));
            return;
        }

        // 创建用于更新数据库数据的对象
        MarketCategory updateCategory = new MarketCategory();
        updateCategory.setId(id);
        updateCategory.setName(name);
        updateCategory.setKeywords(keywords);
        updateCategory.setDesc(desc);
        updateCategory.setIconUrl(iconUrl);
        updateCategory.setPicUrl(picUrl);
        updateCategory.setLevel(level);
        updateCategory.setPid(pid);

        // 修改数据库中的数据
        categoryService.update(updateCategory);
        // 返回响应信息
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.ok()));
    }

    private void create(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = req.getReader().readLine();
        String name = JacksonUtil.parseString(requestBody, "name");
        ObjectMapper objectMapper = JacksonUtil.getObjectMapper();
        MarketCategory marketCategory = objectMapper.readValue(requestBody, MarketCategory.class);

        //校验
        if (StringUtils.isEmpty(name) || name.isEmpty()) {
            Object fail = ResponseUtil.fail(404, "类目名称不能为空");
            resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(fail));
            return;
        }

        // 设置对象属性
        marketCategory.setDeleted(false);
        marketCategory.setSortOrder((byte)50);
        marketCategory.setAddTime(LocalDateTime.now());
        marketCategory.setUpdateTime(LocalDateTime.now());
        // 将对象添加到数据库
        categoryService.create(marketCategory);
        // 返回响应
        Map<String, Object> data = new HashMap<>();
        data.put("id", marketCategory.getId());
        data.put("name", marketCategory.getName());
        data.put("keywords", marketCategory.getKeywords());
        data.put("desc", marketCategory.getDesc());
        data.put("pid", marketCategory.getPid());
        data.put("iconUrl", marketCategory.getIconUrl());
        data.put("picUrl", marketCategory.getPicUrl());
        data.put("level", marketCategory.getLevel());
        data.put("addTime", marketCategory.getAddTime());
        data.put("updateTime", marketCategory.getUpdateTime());
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.ok(data)));
    }
}
